package com.starmark.sys.org.oauth.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.starmark.core.framework.base.AbstractBaseService;
import com.starmark.sys.org.atomic.service.ISysOrgUserService;
import com.starmark.sys.org.oauth.entity.SysOrgOauth;
import com.starmark.sys.org.oauth.mapper.SysOrgOauthMapper;
import com.starmark.sys.org.oauth.service.ISysOrgOauthService;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author starmark
 * @since 2019-07-27
 */
@Service
public class SysOrgOauthServiceImpl extends AbstractBaseService<SysOrgOauthMapper, SysOrgOauth> implements ISysOrgOauthService {

    @Autowired
    private ISysOrgUserService sysOrgUserService;

    @Override
    public void buildPageSearch(Map<String, Object> params, QueryWrapper<SysOrgOauth> eWrapper) {
        if (params.get("keyword") != null && StrUtil.isNotEmpty(params.get("keyword") + "")) {
            eWrapper.like("name", params.get("keyword") + "");
        }

    }

    @Override
    public String getUserId(String openId, String sourceType) {
        Assert.hasText(openId, "第三方系统用户ID为空");
        Assert.hasText(sourceType, "第三方数据来源为空");
        return this.getBaseMapper().getUserId(openId, sourceType);
    }

   /** @EventListener
    public void handleOauthEvent(SysOrgOauthEvent oauthEvent) {
        String userId = this.getUserId(oauthEvent.getAuthUser().getUuid(), oauthEvent.getSourceType());
        //如果用户ID没有值,刚生成登陆数据
        if (StrUtil.isEmpty(userId)) {
            userId = this.buildOauthUser(oauthEvent);
        }
        Assert.hasText(userId, "插入Oauth的用户失败");
        oauthEvent.setUserId(userId);

    }

    private String buildOauthUser(SysOrgOauthEvent oauthEvent) {
        SysOrgUser sysOrgUser = BeanMapper.map(oauthEvent.getAuthUser(), SysOrgUser.class);
        sysOrgUser.setStatus(Boolean.TRUE);
        sysOrgUserService.save(sysOrgUser);
        //插入关系
        SysOrgOauth orgOauth = new SysOrgOauth();
        orgOauth.setOpenId(oauthEvent.getAuthUser().getUuid());
        orgOauth.setUserId(sysOrgUser.getId());
        orgOauth.setSourceType(oauthEvent.getSourceType());
        this.save(orgOauth);
        return sysOrgUser.getId();

    }
   */
}
